package com.kynnnn.cloud.mybatis_interceptor.interceptor;

import com.kynnnn.cloud.mybatis_interceptor.annotation.EncryptDecryptClass;
import com.kynnnn.cloud.mybatis_interceptor.util.EncryptDecryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.util.Objects;
import java.util.Properties;

/**
 * <h1>参数加密拦截器</h1>
 *
 * @author Zhudiwei
 * @Description TODO
 * @createTime 2021年09月04日
 */
@Component
@Slf4j
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class),
})
public class ParameterInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        log.debug(">>>>> 进入参数拦截器的拦截方法 <<<<<");

        if (invocation.getTarget() instanceof ParameterHandler) {
            ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();

            // 通过反射获取对象
            Field parameterField = parameterHandler.getClass().getDeclaredField("parameterObject");
            parameterField.setAccessible(true);
            Object parameterObject = parameterField.get(parameterHandler);

            if (Objects.nonNull(parameterObject)) {
                Class<?> parameterObjectClass = parameterObject.getClass();
                if (parameterObjectClass.isAnnotationPresent(EncryptDecryptClass.class)) {
                    Field[] fields = parameterObjectClass.getDeclaredFields();
                    EncryptDecryptUtils.encrypt(fields, parameterObject);
                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
